import { checkAllCartAPI, deleteCartAPI, findCartListAPI, getNewCartGoodsAPI, insertCartAPI, mergeCartAPI, updateCartAPI } from '@/api/cart'

// 购物车模块
export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品列表
      list: []
    }
  },
  // 本地：id skuId name picture price nowPrice count attrsText selected stock isEffective
  mutations: {
    INSERT_CART (state, payload) {
      // 先找是否有相同的商品
      // 如果有，先查询数量，再累加到payload再保存
      // 如果没有，直接追加到最新位置
      const sameIndex = state.list.findIndex(item => item.skuId === payload.skuId)
      // 逻辑：有相同的给goods累加数量，删除相同skuId的商品
      if (sameIndex >= 0) {
        payload.count = state.list[sameIndex].count + payload.count
        state.list.splice(sameIndex, 1)
      }
      state.list.unshift(payload)
    },

    // 更新购物车
    UPDATE_CART (state, goods) {
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (goods[key] !== undefined && goods[key] !== null && goods[key] !== '') {
          updateGoods[key] = goods[key]
        }
      }
    },

    // 删除购物车
    DELETE_CART (state, skuId) {
      const index = state.list.find(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },

    // 设置购物车
    SET_CART (state, payload) {
      state.list = payload
    }
  },
  actions: {
    // 合并购物车
    async mergeCart (context) {
      const cartList = context.state.list.map(goods => {
        return {
          skuId: goods.skuId,
          selected: goods.selected,
          count: goods.count
        }
      })
      await mergeCartAPI(cartList)
      // 清空本地购物车
      context.commit('SET_CART', [])
    },
    // 修改sku规格函数
    updateCartSku (ctx, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          // 1. 获取旧的商品信息
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          // 2. 删除旧的商品
          deleteCartAPI([oldGoods.skuId]).then(() => {
            // 3. 合并一条新的商品信息
            // 4. 去插入即可
            insertCartAPI({ skuId: newSku.skuId, count: oldGoods.count }).then(() => {
              this.dispatch('cart/findCart')
              resolve()
            })
          })
        } else {
          // 本地
          // 但你修改了sku的时候其实skuId需要更改，相当于把原来的信息移出，创建一条新的商品信息。
          // 1. 获取旧的商品信息
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          // 2. 删除旧的商品
          ctx.commit('DELETE_CART', oldSkuId)
          // 3. 合并一条新的商品信息
          const { skuId, price: nowPrice, inventory: stock, specsText: attrsText } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, stock, attrsText }
          // 4. 去插入即可
          ctx.commit('INSERT_CART', newGoods)
        }
      })
    },
    // 批量删除
    batchDeleteCart (context, isClear) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录
          const ids = context.getters[isClear ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCartAPI(ids).then(() => {
            this.dispatch('cart/findCart')
            resolve()
          })
        } else {
          // 本地
          context.getters[isClear ? 'invalidList' : 'selectedList'].forEach(item => {
            context.commit('DELETE_CART', item.skuId)
          })
          resolve()
        }
      })
    },
    // 有效商品的全选&反选
    checkAllCart (context, selected) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录
          const ids = context.getters.validList.map(item => item.skuId)
          checkAllCartAPI({ selected, ids }).then(() => {
            this.dispatch('cart/findCart')
            resolve()
          })
        } else {
          // 本地
          // 1. 获取有效的商品列表，遍历的去调用修改mutations即可
          context.getters.validList.forEach(item => {
            context.commit('UPDATE_CART', { skuId: item.skuId, selected })
          })
          resolve()
        }
      })
    },

    updateCart (context, payload) {
      return new Promise((resolve, reject) => {
        // 已登陆
        if (context.rootState.user.profile.token) {
          updateCartAPI(payload).then(() => {
            this.dispatch('cart/findCart')
            resolve()
          })
        } else {
          // 未登录
          context.commit('UPDATE_CART', payload)
          resolve()
        }
      })
    },

    insertCart (context, payload) {
      return new Promise((resolve, reject) => {
        // 已登陆
        if (context.rootState.user.profile.token) {
          insertCartAPI({ skuId: payload.skuId, count: payload.count }).then(() => {
            this.dispatch('cart/findCart')
            resolve()
          })
        } else {
          // 未登录
          context.commit('INSERT_CART', payload)
          resolve()
        }
      })
    },

    findCart (context) {
      return new Promise((resolve, reject) => {
        // 已登陆
        if (context.rootState.user.profile.token) {
          findCartListAPI().then(data => {
            context.commit('SET_CART', data.result)
            resolve(data)
          })
        } else {
          // 未登录
          // 同时发送请求，等所有结果请求成功
          const promiseArr = context.state.list.map(goods => {
            return getNewCartGoodsAPI(goods.skuId)
          })
          Promise.all(promiseArr).then(results => {
            results.forEach((goods, i) => {
              context.commit('UPDATE_CART', { skuId: context.state.list[i].skuId, ...goods.result })
            })
          })
          resolve()
        }
      })
    },

    deleteCart (context, payload) {
      // 单条删除
      return new Promise((resolve, reject) => {
        // 已登陆
        if (context.rootState.user.profile.token) {
          deleteCartAPI([payload]).then(() => {
            this.dispatch('cart/findCart')
            resolve()
          })
        } else {
          // 未登录
          context.commit('DELETE_CART', payload)
          resolve()
        }
      })
    }
  },
  getters: {
    // 有效列表
    validList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },

    // 商品总数
    validTotal (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },

    // 总金额
    totalMoney (state, getters) {
      return getters.validList.reduce((p, c) => p + (c.count * c.price), 0)
    },

    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => item.stock <= 0 || !item.isEffective)
    },

    // 已选择商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },

    // 已选商品总数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },

    // 已选择商品的总金额
    selectedMoney (state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.count * c.price), 0)
    },

    // 是否全选
    selectedAll (state, getters) {
      return getters.validList.length !== 0 && (getters.selectedList.length === getters.validList.length)
    }
  }
}
